'use client';

import { useEffect, useState } from 'react';
import { useParams } from 'next/navigation';
import { Card, CardContent, Typography, CircularProgress, Alert, Box, Container } from '@mui/material';
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';
import { getExamStatistics } from '@/api/exam';

interface ExamStatistics {
  scoreDistribution: { score: number; count: number }[];
  passRate: number;
  averageScore: number;
  totalStudents: number;
  highestScore: number;
  lowestScore: number;
}

export default function ExamStatisticsPage() {
  const { id } = useParams();
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [statistics, setStatistics] = useState<ExamStatistics | null>(null);

  useEffect(() => {
    const fetchStatistics = async () => {
      try {
        const data = await getExamStatistics(Number(id));
        setStatistics(data);
        setError(null);
      } catch (err) {
        setError('获取考试统计数据失败');
      } finally {
        setLoading(false);
      }
    };

    fetchStatistics();
  }, [id]);

  if (loading) {
    return (
      <Box display="flex" justifyContent="center" alignItems="center" minHeight="100vh">
        <CircularProgress size={60} />
      </Box>
    );
  }

  if (error) {
    return (
      <Box p={4}>
        <Alert severity="error">{error}</Alert>
      </Box>
    );
  }

  if (!statistics) {
    return (
      <Box p={4}>
        <Alert severity="info">暂无统计数据</Alert>
      </Box>
    );
  }

  return (
    <Box sx={{ p: 6, '& > *': { mb: 6 } }}>
      <Typography variant="h4" gutterBottom>考试统计分析</Typography>

      <Box sx={{ display: 'grid', gridTemplateColumns: { xs: '1fr', md: '1fr 1fr', lg: 'repeat(4, 1fr)' }, gap: 4 }}>
        <Card>
          <CardContent>
            <Typography variant="subtitle1" color="text.secondary">参考人数</Typography>
            <Typography variant="h5">{statistics.totalStudents}</Typography>
          </CardContent>
        </Card>
        <Card>
          <CardContent>
            <Typography variant="subtitle1" color="text.secondary">平均分</Typography>
            <Typography variant="h5">{statistics.averageScore.toFixed(1)}</Typography>
          </CardContent>
        </Card>
        <Card>
          <CardContent>
            <Typography variant="subtitle1" color="text.secondary">及格率</Typography>
            <Typography variant="h5">{(statistics.passRate * 100).toFixed(1)}%</Typography>
          </CardContent>
        </Card>
        <Card>
          <CardContent>
            <Typography variant="subtitle1" color="text.secondary">分数区间</Typography>
            <Typography variant="h5">{statistics.lowestScore} - {statistics.highestScore}</Typography>
          </CardContent>
        </Card>
      </Box>

      <Card>
        <CardContent>
          <Typography variant="h6" gutterBottom>成绩分布</Typography>
          <Box sx={{ height: 400 }}>
            <ResponsiveContainer width="100%" height="100%">
            <BarChart data={statistics.scoreDistribution}>
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis dataKey="score" label={{ value: '分数', position: 'insideBottom', offset: -5 }} />
              <YAxis label={{ value: '人数', angle: -90, position: 'insideLeft' }} />
              <Tooltip />
              <Legend />
              <Bar dataKey="count" name="人数" fill="#8884d8" />
            </BarChart>
          </ResponsiveContainer>
        </Box>
      </CardContent>
    </Card>
    </Box>
  );
}